package com.changgou.search.controller;

import com.changgou.entity.Page;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.ESManagerService;
import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;
import java.util.Set;

/**
 * @Author: HuangFu
 * @Date: 2020/2/2 20:16
 * @Description:
 */
@Controller
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private ESManagerService esManagerService;
    @Autowired
    private SearchService searchService;

    /**
     * 查询参数拦截，处特殊符号
     * @param searchMap
     */
    public void handlerSearchMap(Map<String,String> searchMap){
        if(searchMap!=null){
            Set<Map.Entry<String, String>> entries = searchMap.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                if(entry.getKey().startsWith("spec_")){
                    searchMap.put(entry.getKey(),entry.getValue().replace("+","%2B"));
                }
            }
        }

    }


    @GetMapping
    @ResponseBody
    public Map search(@RequestParam Map<String,String> paramMap) throws Exception{
        //特殊符号处理
        this.handlerSearchMap(paramMap);
        return searchService.search(paramMap);
    }

    @GetMapping("/list")
    public String list(@RequestParam Map<String,String> paramMap, Model model) throws Exception{
        //特殊符号处理
        this.handlerSearchMap(paramMap);

        Map resultMap = searchService.search(paramMap);

        model.addAttribute("searchMap",paramMap);
        model.addAttribute("result",resultMap);

        //设置分页对象
        Page<SkuInfo> skuInfoPagee = new Page<>(Long.valueOf(resultMap.get("total").toString()),Integer.valueOf(resultMap.get("pageNum").toString()),Page.pageSize);
        model.addAttribute("page",skuInfoPagee);

        //封装当前请求URL
        StringBuilder sb = new StringBuilder();
        sb.append("/search/list");
        if(paramMap!=null&&paramMap.size()>0){
            sb.append("?");
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                //出去特殊字段
                if (!"sortRule".equals(entry.getKey()) && !"sortField".equals(entry.getKey()) && !"pageNum".equals(entry.getKey())) {
                    sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
            }
            //设置请求地址，除去最后一位
            model.addAttribute("url",sb.toString().substring(0,sb.toString().length()-1));
        }


        return "search";
    }
}
